# -*- coding:utf-8 -*-
from userprofile.models import Menu
from django.contrib.auth.models import User
import datetime
import socket
import functools


def get_user_menus(user):
    """
    获取用户菜单, 需要从角色权限和用户权限两张表中取并集
    :param user:
    :return:
    """
    privilege_menu = []
    privilege_update = {}
    maxrole = None
    user_profile = User.objects.get(id=user.id)
    user_roles = user_profile.userprofile.role.all()

    # 遍历角色功能权限
    for role in user_roles:
        # 获取最大权限的角色id
        if not maxrole:
            maxrole = role.id
        if role.id < maxrole:
            maxrole = role.id
        # 获取角色限权
        for permission in role.rolemenu_set.all():  # 角色权限
            if permission.get == '1':
                privilege_update.update({permission.menu.url: {'get': permission.get, 'post': permission.post,
                                                               'put': permission.put, 'delete': permission.delete}})

    # 遍历用户功能权限
    permissions = user_profile.usermenu_set.all()  # 用户权限
    for permission in permissions:
        if permission.get == '1':
            # 取 用户和角色 的并集
            if privilege_update.get(permission.menu.url):
                if permission.get == '1':
                    privilege_update[permission.menu.url]['get'] = '1'
                if permission.post == '1':
                    privilege_update[permission.menu.url]['post'] = '1'
                if permission.put == '1':
                    privilege_update[permission.menu.url]['put'] = '1'
                if permission.delete == '1':
                    privilege_update[permission.menu.url]['delete'] = '1'
            else:
                privilege_update.update({permission.menu.url: {'get': permission.get, 'post': permission.post,
                                                               'put': permission.put,
                                                               'delete': permission.delete}})
    menus = Menu.objects.filter(parent=None).all()
    for menu in menus:
        user_menu = {'id': menu.id, 'name': menu.name, 'url': menu.url, 'icon': menu.icon, 'weight': 1}
        sub_menus = Menu.objects.filter(parent=menu).all()
        children = []
        for sub_menu in sub_menus:
            user_child_menu = {'id': sub_menu.id, 'name': sub_menu.name, 'url': sub_menu.url, 'icon': menu.icon,
                               'weight': 0}
            if privilege_update.get(sub_menu.url) and privilege_update[sub_menu.url]['get'] == '1':
                user_child_menu.update(privilege_update[sub_menu.url])
                children.append(user_child_menu)
        user_menu['children'] = children
        if privilege_update.get(menu.url) and privilege_update[menu.url]['get'] == '1':
            user_menu.update(privilege_update[menu.url])
            privilege_menu.append(user_menu)
    # print('-----', privilege_menu)
    return privilege_menu, privilege_update, maxrole


def permission_required(func):
    """
    权限预处理
    """
    # 保留原有函数的名称和docstring
    @functools.wraps(func)
    def __wrapper(*args, **kwargs):
        request = args[0]  # same to request
        permission = request.session['permission']
        url = request.path
        request.session['user_permission'] = permission.get(url, {})
        user_menus = request.session['menus']
        parent_active = False
        for menu in user_menus:
            for sub_menu in menu['children']:
                if sub_menu['url'] == url:
                    parent_active = True
        request.session['parent_active'] = parent_active
        response = func(*args, **kwargs)
        return response
    return __wrapper


def get_days(start_at, end_at):
    """
    获取时间段内的天数
    :param start_at:
    :param end_at:
    :return:
    """
    days = []
    if isinstance(start_at, str):
        start_at = datetime.datetime.strptime(start_at, '%Y-%m-%d %H:%M:%S')
    if isinstance(end_at, str):
        end_at = datetime.datetime.strptime(end_at, '%Y-%m-%d %H:%M:%S')
    while True:
        if start_at > end_at:
            break
        days.append(start_at.strftime('%Y-%m-%d'))
        start_at += datetime.timedelta(days=1)
    return days

if __name__=='__main__':
    # print(get_days('2017-03-02','2017-03-10'))
        get_days('2017-03-02', '2017-03-10')